package com.example.demo.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.io.InputStream;

/**
 * http://hc.apache.org/httpcomponents-client-ga/examples.html
 *
 * @author Created by niugang on 2020/3/24/11:13
 * 此示例演示了在手动处理HTTP响应的情况下如何确保将基础HTTP连接释放回连接管理器。
 */
public class ClientConnectionRelease {
    public final static void main(String[] args) throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet("http://httpbin.org/get");

            System.out.println("Executing request " + httpget.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());

                // 获取响应实体
                HttpEntity entity = response.getEntity();
                //如果响应未包含实体，则无需担心连接释放
                if (entity != null) {
                    InputStream inStream = entity.getContent();
                    try {
                        inStream.read();
                        // do something useful with the response
                    } catch (IOException ex) {
                        //如果发生IOException，则连接将自动释放回连接管理器
                        throw ex;
                    } finally {
                        // 关闭输入流将触发连接释放
                        inStream.close();
                    }
                }
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }


}
